import {
    fetchGameDetailReq,
    getGameRoomChatTokenReq,
    matchGuessReq,
    fetchMatchGuessReq,
    fetchGameAiReq,
    buyGameAiReq,
    markGameReq,
    fetchMarkGameListReq,
    getAIResultListReq,
    getHotAiListReq,
    getMyAIListNotStartReq,
    getMyAIListFinishedReq,
    fetchGameAiBuyReq,
    getGameLiveListReq,
    fetchGameListLiveReq,
    fetchGameOddsHistoryReq,
    fetchGameListReq,
    getGameIntelligenceReq, getGameAnalysis, getGameOddsList,
    getBasketballGameDetailReq,
} from "../apis/goApis";
import {
    fetchNanoGameListReq,
    fetchOddsListAllReq,
    fetchOddsEuroLiveReq,
    fetchOddsEuroReq,
    fetchEventListReq,
} from "../apis/nanoApi";
import {handleResp, compareArray} from "../utils/commonfunc";
import {formatDate} from "../utils/dateService";
import LocalStorageService from "../utils/LocalStorageService";

export const NANO_GAME_STATUS_CODE = {
    0: '比赛异常',
    1: '未开赛',
    2: '上半场',
    3: '中场',
    4: '下半场',
    5:	'加时赛',
    6:	'加时赛',
    7:	'点球决战',
    8:	'完场',
    9:	'推迟',
    10:	'中断',
    11:	'腰斩',
    12:	'取消',
    13:	'待定',
}

export const NANO_GAMES_TECH_CODE = {
    1:	'进球',
    2:	'角球',
    3:	'黄牌',
    4:	'红牌',
    5:	'界外球',
    6:	'任意球',
    7:	'球门球',
    8:	'点球',
    9:	'换人',
    10:	'比赛开始',
    11:	'中场',
    12:	'结束',
    13:	'半场比分',
    15:	'两黄变红',
    16:	'点球未进',
    17:	'乌龙球',
    19:	'伤停补时',
    21:	'射正',
    22:	'射偏',
    23:	'进攻',
    24:	'危险进攻',
    25:	'控球率',
    26:	'加时赛结束',
    27:	'点球大战结束',
}

export const NANO_ODDS_COMPANY_CODE = {
    2: 'BET365',
    3: '皇冠',
    4: '10BET',
    5: '立博',
    6: '明陞',
    7: '澳彩',
    8: 'SNAI',
    9: '威廉希尔',
    10:	'易胜博',
    11:	'韦德',
    12:	'EuroBet',
    13:	'Inter wetten',
    14:	'12bet',
    15:	'利记',
    16:	'盈禾',
    17:	'18Bet',
    18:	'Fun88',
    19:	'竞彩官方',
    21:	'188',
    22:	'平博',
}

export const ICON_URL_PREFIX = 'http://cdn.sportnanoapi.com/football/team/'

const now = new Date()
const today = formatDate(now)
const initCurrentGame =  {
    mark: false,

    info: {
        matchtime: '',
            realtime: '',
            round: 0,
            statusid: 999,
            environment: {
            pressure: '',
                temperature: '',
                wind: '',
                humidity: '',
                weather_id: '',
                weather: '',
                weather_image: '',
        }
    },

    matchevent: {
        season: '',
            id: '',
            name_zh: '',
    },

    home_team: {
        logo: '',
            score: '',
            half_score: '',
            id: '',
            name_zh: '',
    },

    away_team: {
        logo: '',
            score: '',
            half_score: '',
            id: '',
            name_zh: '',
    },

    tlive: [
        {
            "main": 0,
            "data": '',
            "position": 0,
            "type": 0,//事件类型
            "time": "'"//事件时间
        }
    ],

    stats: [
        // {
        //     home: 0,
        //     away: 0,
        //     type: 0,
        // },
        //
        {home: 0, away: 0, type: 2},
        {home: 0, away: 0, type: 3},
        {home: 0, away: 0, type: 4},
        {home: 0, away: 0, type: 8},
        {home: 0, away: 0, type: 21},
        {home: 0, away: 0, type: 22},
        {home: 0, away: 0, type: 23},
        {home: 0, away: 0, type: 24},
        {home: 0, away: 0, type: 25},
    ],

    odds: {
        // 0: {}
    },

    lineUp: {

    },

    analysis: {

        teams: {
            0: {
                id: 0, //球队id
                    "name_zh": "", //中文名称
                    "name_zht": "", //粤语名称
                    "name_en": "FC Barcelona", //英文名称
                    "logo": "d159737531127e403115903764cb5145.png", //logo,url前缀:http://cdn.sportnanoapi.com/football/team/
                    "matchevent_id": 120, //赛事id
            },
        },

        events: {
            0: {
                "id": 24, //赛事id
                    "name_zh": "", //中文名称
                    "short_name_zh": "", //中文简称
                    "name_zht": "", //粤语名称
                    "short_name_zht": "", //粤语简称
                    "name_en": "", //英文名称
                    "short_name_en": "", //英文简称
                    "logo": "" // logo,url前缀:http://cdn.sportnanoapi.com/football/competition/
            },
        },

        info: {
            matchtime: '',
                realtime: '',
                round: 0,
                statusid: 8,
                environment: {
                pressure: '',
                    temperature: '',
                    wind: '',
                    humidity: '',
                    weather_id: '',
                    weather: '',
                    weather_image: '',
            }
        },

        history: {

        },

        goal_distribution: {

        },

        injury: {

        },

        table: {

        },


    },

    guess: {

    },

    intelligence: {
        info: {
            good: {
                home: [],
                away: [],
            },
            bad: {
                home: [],
                away: [],
            },
            neutral: [],
        },
    },

    ai: {
        'RQ': {
            cost: 30,
            title: '让球',
            type: 1,
            // available: true,
            // paid: true,
            // correct: true,
            data: {
                home: 0,
                tied: 0,
                away: 0,
            }
        },
        'SFP': {
            cost: 30,
            title: '胜平负',
            type: 2,
            // available: true,
            // paid: false,
            // correct: false,
            data: {
                home: 0,
                tied: 0,
                way: 0,
            }
        },
        'DXQ': {
            cost: 30,
            title: '大小球',
            type: 3,
            // available: true,
            // paid: true,
            // correct: true,
            data: {
                home: 0,
                tied: 0,
                away: 0,
            }
        }
    }

}

// const today = '2019-11-29'
export const game = {

    state: {

        searchQuery: '',

        tabPosition: [0, 0, {
            schedule: 0,
            result: 3,
        },],

        markList: [],

        eventFilters: [],

        today: today,

        update: '',

        events: {

        },

        lives: [],

        odds: [],

        games: {
            [today]: {

                matches: [],

                events: {
                    0: {
                        "id": 24, //赛事id
                        "name_zh": "", //中文名称
                        "short_name_zh": "", //中文简称
                        "name_zht": "", //粤语名称
                        "short_name_zht": "", //粤语简称
                        "name_en": "", //英文名称
                        "short_name_en": "", //英文简称
                        "logo": "" // logo,url前缀:http://cdn.sportnanoapi.com/football/competition/
                    },
                },

                teams: {
                    0: {
                        id: 0, //球队id
                        "name_zh": "", //中文名称
                        "name_zht": "", //粤语名称
                        "name_en": "FC Barcelona", //英文名称
                        "logo": "d159737531127e403115903764cb5145.png", //logo,url前缀:http://cdn.sportnanoapi.com/football/team/
                        "matchevent_id": 120, //赛事id
                    },
                },

                stages: {
                    0: {
                        "id": 0, //id
                        "mode": 0, //比赛方式, 1-积分 2-淘汰
                        "group_count": 0, //总分组数,0表示没有分组
                        "round_count": 0,//总轮数,0表示没有轮次
                        "name_zh": "", //中文名称
                        "name_zht": "", //粤语名称
                        "name_en": "Groups" //英文名称
                    },
                },

            },
        },

        currentGame: initCurrentGame,

        intelligence: {

        },

        chatRoomToken: '',

        aiResult: {
            list: [],
        },

        hotAi: {
            list: [],
            p: 0,
            s: 0,
        },

        myAI: {
            0: {},
            1: {},
        }
    },

    reducers: {

        setToday(state, payload) {
            return {
                ...state,
                today: payload.today,
            }
        },

        setSearchQuery(state, payload) {
            return {
                ...state,
                searchQuery: payload,
            }
        },

        setGameTabPosition(state, payload) {


            const {
                position,
                depth,
                type,
            } = payload

            let tabPosition = [...state.tabPosition]
            if (depth > 1) {
                tabPosition[depth][type] = position
            } else {
                tabPosition[depth] = position
            }


            return {
                ...state,
                tabPosition,
            }

        },

        setGameTabPositionInit(state, payload) {
            return {
                ...state,
                tabPosition: [0, 0, {
                    schedule: 0,
                    result: 3,
                },],
            }
        },

        setEventFilter(state, payload) {
            const {
                eventFilters,
            } = payload
            return {
                ...state,
                eventFilters,
            }
        },

        setMarkList(state, payload) {
            const list = payload.ok
            LocalStorageService.markGameList(list)
            return {
                ...state,
                markList: list,
            }
        },

        setOneDayMarkList(state, payload) {
            const markList = [...state.markList]
            const date = payload.date
            const i = markList.findIndex(list => list[0] === date)
            markList[i] = [date, ...payload.list]
            return {
                ...state,
                markList: markList,
            }
        },

        setVodLiveList(state, payload) {
            return {
                ...state,
                lives: payload.lives,
            }
        },

        setGameList(state, payload) {

            const {
                teams,
                events,
                matches,
                stages,
                date,
                lives,
                odds,
            } = payload


            let storage = LocalStorageService
            let loginKey = 'isLogin'
            let login = storage.get(loginKey)

            matches.forEach((match, index) => {match.push(index)})

            if (login) {
                let key = 'follow_games'
                let mark = storage.get(key)
                // let markDate
                if (mark) {
                    let markDate = storage.get(key)[date]

                    matches.forEach((match, index) => {

                        let id = match[0]
                        if (markDate) {
                            let i = markDate.findIndex(game => game.matchId === id)
                            if (i > -1) {
                                const gameObjInit = GameDataArrayToObject(match)
                                const gameObjFinal = GameDataObjectFinalized(gameObjInit, teams, events, stages)
                                markDate[i] = gameObjFinal
                            }
                        }

                    })

                    mark[date] = markDate

                    storage.save(key, mark)
                } else {
                    mark = {}
                }

            }

            return {
                ...state,
                lives,
                odds: {
                    ...state.odds,
                    [date]: odds,
                },
                games: {
                    ...state.games,
                    [date]: {
                        ...state.games[date],
                        teams,
                        events,
                        matches,
                        stages,
                    },
                },
            }
        },

        setGameListUpdate(state, payload) {

            const {
                date,
                matchesUpdate,
            } = payload

            // console.log(payload)


            const todayMatches = [...state.games[date].matches]

            if (matchesUpdate.length === 0) {
                return {
                    ...state,
                }
            }

            let update = []

            // eslint-disable-next-line array-callback-return
            matchesUpdate.map(match => {

                const matchId = match[0]
                const index = todayMatches.findIndex(m => m[0] === matchId)

                if (index > -1) {

                    const matchToUpdate = todayMatches[index]

                    const matchStatusUpdate = match[1]
                    const homeTeamDataUpdate = match[2]
                    const awayTeamDataUpdate = match[3]
                    const stateAtUpdate = match[4]

                    const currentHomeTeamData = matchToUpdate[5]
                    const currentAwayTeamData = matchToUpdate[6]
                    const homeTeamDateNewest = [...currentHomeTeamData.slice(0, 2), ...homeTeamDataUpdate]
                    const awayTeamDateNewest = [...currentAwayTeamData.slice(0, 2), ...awayTeamDataUpdate]

                    if (matchToUpdate[2] !== matchStatusUpdate) {
                        matchToUpdate[2] = matchStatusUpdate
                    }

                    if (matchToUpdate[4] !== stateAtUpdate) {
                        matchToUpdate[4] = stateAtUpdate
                    }

                    const isHomeTeamUpdate = !compareArray(currentHomeTeamData, homeTeamDateNewest)
                    if (isHomeTeamUpdate) {
                        // eslint-disable-next-line array-callback-return
                        currentHomeTeamData.map((e, i) => {

                            let old = e
                            let cur = homeTeamDateNewest[i]

                            // update = [
                            //     matchToUpdate,
                            //     homeTeamDateNewest,
                            // ]

                            if (i === 2 && old !== cur) {
                                update = [
                                    matchToUpdate,
                                    homeTeamDateNewest,
                                ]
                            }

                        })
                        matchToUpdate[5] = homeTeamDateNewest
                    }


                    const isAwayTeamUpdate = !compareArray(currentAwayTeamData, awayTeamDateNewest)
                    if (isAwayTeamUpdate) {
                        // eslint-disable-next-line array-callback-return
                        currentAwayTeamData.map((e, i) => {

                            let old = e
                            let cur = awayTeamDateNewest[i]

                            // update = [
                            //     matchToUpdate,
                            //     awayTeamDateNewest,
                            // ]

                            if (i === 2 && old !== cur) {
                                update = [
                                    matchToUpdate,
                                    awayTeamDateNewest,
                                ]
                            }

                        })
                        matchToUpdate[6] = awayTeamDateNewest
                    }
                }
            })

            return {
                ...state,
                update,
                games: {
                    ...state.games,
                    [date]: {
                        ...state.games[date],
                        matches: todayMatches,
                    }
                }
            }
        },

        setCurrentGame(state, payload) {
            // if (payload)
            return {
                ...state,
                currentGame: {
                    ...state.currentGame,
                    ...payload.game,
                }
            }
        },

        setCurrentGameErr(state, payload) {
            return {
                ...state,
                currentGame: {
                    ...state.currentGame,
                    err: payload.game.err
                },
            }
        },

        setGameOddsList(state, payload) {
            return {
                ...state,
                currentGame: {
                    ...state.currentGame,
                    odds: payload.odds,
                }
            }
        },

        setCurrentGameAnalysis(state, payload) {
            return {
                ...state,
                currentGame: {
                    ...state.currentGame,
                    analysis: payload.analysis,
                }
            }
        },

        setCurrentGameIntelligence(state, payload) {
            return {
                ...state,
                currentGame: {
                    ...state.currentGame,
                    intelligence: payload.intelligence,
                }
            }
        },

        setInitCurrentGame(state, payload) {
            return {
                ...state,
                currentGame: initCurrentGame,
                chatRoomToken: '',
            }
        },

        setChatToken(state, payload) {
            return {
                ...state,
                chatRoomToken: payload,
            }
        },

        setMatchGuess(state, payload) {
            return {
                ...state,
                currentGame: {
                    ...state.currentGame,
                    guess: {
                        ...state.currentGame.guess,
                        // ...payload
                        guessed: payload.guessed,
                        ...payload.ok,
                    },
                }
            }
        },

        setUserMatchGuess(state, payload) {
            return {
                ...state,
                currentGame: {
                    ...state.currentGame,
                    guess: {
                        ...state.currentGame.guess,
                        // ...payload
                        // ...payload,
                        Guesswin: Number(payload.ok.guesswin),
                        Guesstie: Number(payload.ok.guesstie),
                        Guesslose: Number(payload.ok.guesslose),
                        guessed: true,
                    },
                }
            }
        },

        setMatchAI(state, payload) {

            // const {
            //     buy,
            //     datastate,
            //     cost,
            // } = payload

            // D: (3) [0.57, 2.5, 1.25]
            // Dbuy: 0
            // Dret: 1
            // R: (3) [0.86, 0.75, 1.01]
            // Rbuy: 0
            // Rret: 1
            // S: (3) [1.67, 3.8, 3.85]
            // Sbuy: 0
            // Sret: 1
            const data = payload.ok
            const cost = payload.cost

            let newRQ, newSFP, newDXQ
            if (data === undefined) {
                newRQ = {
                    dataEmpty: true,
                }
                newSFP = {
                    dataEmpty: true,
                }
                newDXQ = {
                    dataEmpty: true,
                }
            }

            // const [RQData, SFPData, DXQData,] = datastate
            const RQData = data.R
            const SFPData = data.S
            const DXQData = data.D

            // const [RQPaid, SFPPaid, DXQPaid,] = buy
            const RQPaid = data.Rbuy
            const SFPPaid = data.Sbuy
            const DXQPaid = data.Dbuy

            if (RQData === null) {
                newRQ = {
                    dataEmpty: true,
                }
            } else {
                const RQ = payload.ok.R

                if (RQPaid === 0) {
                    newRQ = {
                        // title: '让球',
                        correct: payload.ok.Rret,
                        data: {rateArr: RQ},
                        paid: false,
                    }

                } else {
                    // const RQ = payload.ok.R
                    const RQHomeRate = RQ[0]
                    const RQAwayRate = RQ[2]
                    const RQTotal = RQHomeRate + RQAwayRate
                    let RQHome = Number((RQAwayRate / RQTotal).toFixed(2))
                    // console.log(RQHome)
                    let RQAway = Number((RQHomeRate / RQTotal).toFixed(2))
                    // console.log(RQAway)

                    newRQ = {
                        // ...RQ,
                        // title: '让球',
                        // available: true,
                        cost,
                        correct: payload.ok.Rret,
                        paid: true,
                        data: {
                            rateArr: RQ,
                            home: RQHome,
                            away: RQAway,
                            tied: 0,
                        }
                    }
                }
            }

            if (SFPData === null) {

                newSFP = {
                    dataEmpty: true,
                }

            } else {
                const SFP = payload.ok.S

                if (SFPPaid === 0) {

                    newSFP = {
                        data: {rateArr: SFP},
                        paid: false,
                        correct: payload.ok.Sret,
                    }

                } else {

                    // const SFP = payload.ok.S
                    const [SFPHomeRate, SFPTiedRate, SFPAwayRate,] = SFP
                    let SFPTotal = SFPHomeRate + SFPTiedRate + SFPAwayRate
                    let SFP1 = Number((SFPHomeRate / SFPTotal).toFixed(2))
                    let SFP2 = Number((SFPTiedRate / SFPTotal).toFixed(2))
                    let SFP3 = Number((SFPAwayRate / SFPTotal).toFixed(2))
                    let SArray = [SFP1, SFP2, SFP3]
                    let sortedS = [...SArray].sort((a, b) => a - b)
                    const smallest = sortedS[0]
                    const largest = sortedS[2]
                    const smallestIndex = SArray.findIndex(e => e === smallest)
                    const largestIndex = SArray.findIndex(e => e === largest)
                    SArray[smallestIndex] = largest
                    SArray[largestIndex] = smallest
                    let [SFPHome, SFPTied, SFPAway] = SArray
                    newSFP = {
                        paid: true,
                        correct: payload.ok.Sret,
                        cost,
                        data: {
                            rateArr: SFP,
                            home: SFPHome,
                            away: SFPAway,
                            tied: SFPTied,
                        }
                    }

                }

            }

            if (DXQData === null) {

                newDXQ = {
                    dataEmpty: true,
                }

            } else {
                const DXQ = payload.ok.D

                if (DXQPaid === 0) {

                    newDXQ = {
                        data: {rateArr: DXQ,},
                        paid: false,
                        correct: payload.ok.Dret,
                    }

                } else {
                    const DXQHomeRate = DXQ[0]
                    const DXQAwayRate = DXQ[2]
                    const DXQTotal = DXQHomeRate + DXQAwayRate
                    let DXQHome = Number((DXQAwayRate / DXQTotal).toFixed(2))
                    // cons
                    // console.log(RQHome)
                    let DXQAway = Number((DXQHomeRate / DXQTotal).toFixed(2))
                    // console.log(RQAway)
                    newDXQ = {
                        // ...RQ,
                        // title: '让球',
                        // available: true,
                        correct: payload.ok.Dret,
                        paid: true,
                        cost,
                        data: {
                            rateArr: DXQ,
                            home: DXQHome,
                            away: DXQAway,
                            tied: 0,
                        }
                    }
                }

            }


            // const buy = payload.
            // 'RQ': {
            //     title: '让球',
            //         available: true,
            //         paid: true,
            //         correct: true,
            //         data: {
            //         home: 0.67,
            //             tied: 0.22,
            //             away: 0.11,
            //     }
            // },



            return {
                ...state,
                currentGame: {
                    ...state.currentGame,
                    ai: {
                        ...state.currentGame.ai,
                        RQ: {
                            ...state.currentGame.ai.RQ,
                            ...newRQ
                        },
                        SFP: {
                            ...state.currentGame.ai.SFP,
                            ...newSFP,
                        },
                        DXQ: {
                            ...state.currentGame.ai.DXQ,
                            ...newDXQ,
                        }
                    }
                }
            }
        },

        emptyUpdate(state, payload) {
            return {
                ...state,
                update: '',
            }
        },

        setAIResultList(state, payload) {
            const list = payload.ok
            const p = payload.p
            const style = payload.style ? payload.style : 0
            return {
                ...state,
                aiResult: {
                    ...state.aiResult,
                    [style]: {
                        ...state.aiResult[style],
                        [p]: list,
                    }
                }
            }
        },

        setHotAIList(state, payload) {

            return {
                ...state,
                hotAi: {
                    p: payload.p,
                    s: payload.s,

                    list: [...state.hotAi.list, ...payload.ok],
                }
            }
        },

        setMyAIList(state, payload) {
            const {
                type,
                p,
                ok,
            } = payload

            return {
                ...state,
                myAI: {
                    ...state.myAI,
                    [type]: {
                        ...state.myAI[type],
                        [p]: ok,
                    }
                }
            }
        },
    },

    effects: (dispatch) => ({

        updateToday(payload, rootState) {
            dispatch.game.setToday(payload)
        },

        doSearch(payload, rootState) {
            dispatch.game.setSearchQuery(payload)
        },

        changeGameTabPosition(payload, rootState) {

            dispatch.game.setGameTabPosition(payload)
        },

        doGameTabPositionInit(payload, rootState) {
            dispatch.game.setGameTabPositionInit()
        },

        changeEventFilter(payload, rootState) {
            dispatch.game.setEventFilter(payload)
        },

        async doFetchEventList(payload, rootState) {

            const resp = await fetchEventListReq(payload)

            handleResp(resp, dispatch, (data) => {

                // const eventData = JSON.parse(data.ok)

            })

        },

        async doFetchGameVodLiveList(payload, rootState) {
            const resp = await getGameLiveListReq()
            handleResp(resp, dispatch, data => {
                if (data.ok) {
                    let lives = data.ok
                    this.setVodLiveList({
                        lives,
                    })
                }
            })
        },

        async doFetchGameListAll(payload, rootState,) {
            const date = payload.date

            let resp
            let lives = []
            let odds = []

            resp = await fetchGameListReq({
                date,
            }, payload.toast)

            const respLive = await getGameLiveListReq()
            const respOdd = await getGameOddsList({date: payload.date})

            if (respLive.data.ok) {
                lives = respLive.data.ok
            }
            if (respOdd.data.ok) {
                odds = respOdd.data.ok
            }

            const p = new Promise(resolve => {
                handleResp(resp, dispatch, data => {
                    if (data.ok) {
                        // console.log(data.ok)

                        const dataObject = JSON.parse(data.ok)
                        // console.log(dataObject)
                        if (dataObject.err) {
                            // console.log(dataObject.err)
                            return
                        }

                        const teams = dataObject.teams
                        const events = dataObject.events
                        const matches = dataObject.matches
                        const stages = dataObject.stages

                        this.setGameList({
                            date,
                            teams,
                            events,
                            matches,
                            stages,
                            lives,
                            odds,
                        })
                        resolve(true)
                    }
                })
            })
            return p
        },

        async doFetchGameListLive(payload, rootState) {
            let resp = await fetchGameListLiveReq()

            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    const matchesUpdate = JSON.parse(data.ok)
                    dispatch.game.setGameListUpdate({
                        date: today,
                        matchesUpdate,
                    })
                }
            })
        },

        async doFetchGameDetail(payload, rootState) {

            let resp = await fetchGameDetailReq(payload)
            handleResp(resp, dispatch, (data) => {
                const game = JSON.parse(data.ok)
                game.matchId = String(payload.matchid)
                if (game.err) {
                    dispatch.game.setCurrentGameErr({
                        game,
                    })
                } else {
                    dispatch.game.setCurrentGame({
                        game,
                    })
                }
            })
        },

        async doFetchBasketballGameDetail(payload, rootState) {

            const resp = await getBasketballGameDetailReq(payload)
            handleResp(resp, dispatch, (data) => {
                const game = data.ok
                game.matchId = payload.id
                game.home = {
                    name: game.Zhuname,
                    score: [game.Zhufen1, game.Zhufen2, game.Zhufen3, game.Zhufen4, game.Zhufen5,],
                    logo: game.Zhulogo + '0',
                }
                game.away = {
                    name: game.Kename,
                    score: [game.Kefen1, game.Kefen2, game.Kefen3, game.Kefen4, game.Kefen5,],
                    logo: game.Kelogo + '0',
                }
                if (game.err) {
                    dispatch.game.setCurrentGameErr({
                        game,
                    })
                } else {
                    dispatch.game.setCurrentGame({
                        game,
                    })
                }
            })
            return resp
        },

        async doFetchGameAnalysis(payload, rootState) {

            const resp = await getGameAnalysis({matchid: parseInt(payload.id)}, false)

            handleResp(resp, dispatch, (data) => {
                if (data.ok) {

                    const analysis = JSON.parse(data.ok)
                    if (analysis.err) {
                        return
                    }
                    dispatch.game.setCurrentGameAnalysis({analysis,})
                }
            })

        },

        async doFetchGameIntelligence(payload, rootState) {

            // const resp = await fetchGameIntelligence(payload, false)

            const resp = await getGameIntelligenceReq({matchid: parseInt(payload.id)}, false,)
            handleResp(resp, dispatch, (data) => {
                try {
                    const intelligence = JSON.parse(data.ok)
                    dispatch.game.setCurrentGameIntelligence({intelligence,})
                } catch (e) {
                    // dispatch.game.setCurrentGameIntelligence({intelligence: ,})
                }


            })

        },

        async doFetchOddsListAll(payload, rootState) {
            const resp = await fetchOddsListAllReq()
            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    const oddsList = JSON.parse(data.ok)
                }
            })
        },

        async doFetchGamesOddsList(payload, rootState) {
            let resp = await fetchGameOddsHistoryReq({matchid: parseInt(payload.matchId),}, false)

            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    // console.log(data.ok)
                    const oddsList = JSON.parse(data.ok)
                    // console.log('oddsList', oddsList)
                    dispatch.game.setGameOddsList({
                        odds: oddsList,
                    })
                }
            })
        },

        async doFetchOddsEuroLive(payload, rootState) {
            const resp = await fetchOddsEuroLiveReq()
            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    const oddsList = JSON.parse(data.ok)
                }
            })
        },

        async doFetchGameEuroOddsList(payload, rootState) {
            const id = payload.matchId
            const resp = await fetchOddsEuroReq({id,})
            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    const oddsList = JSON.parse(data.ok)
                }
            })
        },

        async doRefreshGameListAll(payload, rootState) {
            const resp = await fetchNanoGameListReq()
        },

        async doGetGameRoomChatToken(payload, rootState) {
            const resp = await getGameRoomChatTokenReq(payload)
            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    const token = data.ok
                    dispatch.game.setChatToken(token)
                }
            })
        },

        async doGuessMatch(payload, rootState) {
            const resp = await matchGuessReq(payload)
            handleResp(resp, dispatch, (data) => {
                if (data.ok) dispatch.game.setUserMatchGuess(data)
            })
        },

        async doFetchMatchGuess(payload, rootState) {
            const resp = await fetchMatchGuessReq(payload)
            handleResp(resp, dispatch, (data) => {
                // console.log(data)
                if (data.ok) dispatch.game.setMatchGuess(data)
            })
        },

        async doFetchGameAiBuy(payload, rootState) {
            const resp = await fetchGameAiBuyReq(payload)
            handleResp(resp, dispatch, (data) => {
            })
        },

        async doFetchGameAi(payload, rootState) {
            const resp = await fetchGameAiReq(payload)
            handleResp(resp, dispatch, (data) => {


                dispatch.game.setMatchAI(data)

            })
        },

        async doBuyGameAi(payload, rootState) {

            const resp = await buyGameAiReq(payload)
            handleResp(resp, dispatch, (data) => {

                dispatch.game.setMatchAI(data)

            })

        },

        async doFetchMarkList(payload, rootState) {
            const resp = await fetchMarkGameListReq(payload)
            handleResp(resp, dispatch, (data) => {
                dispatch.game.setMarkList(data)
            })
        },

        async doMarkGame(payload, rootState) {
            const resp = await markGameReq(payload)
            handleResp(resp, dispatch, (data) => {
                const list = data.ok
                dispatch.game.setOneDayMarkList({date: payload.date, list,})
            })
        },

        doEmptyUpdate(payload, rootState) {
            dispatch.game.emptyUpdate()
        },

        async doGetAIResultList(payload, rootState) {
            const resp = await getAIResultListReq(payload)
            const p = payload.p
            // const style = payload.style
            handleResp(resp, dispatch, (data) => {
                data.p = p
                // data.style = style
                this.setAIResultList(data)
            })
        },

        async doGetHotAIList(payload, rootState) {
            const resp = await getHotAiListReq(payload)
            handleResp(resp, dispatch, (data) => {
                this.setHotAIList(data)
            })
            return resp
        },

        async doGetMyAIList(payload, rootState) {
            let resp
            if (payload.type === 0) {
                resp = await getMyAIListNotStartReq(payload.params)
            } else {
                resp = await getMyAIListFinishedReq(payload.params)
            }
            let p = new Promise((resolve => {
                handleResp(resp, dispatch, (data) => {
                    data.type = payload.type
                    data.p = payload.params.p
                    this.setMyAIList(data)
                    resolve(data)
                    // this.setHotAIList(data)
                })
            }))
            return p
        },


    }),
}


export const teamDataArrayToObject = (array) => {
    const result = {}
    const [
        teamId,
        teamRankInLeague,
        teamScore,
        teamScoreHalf,
        red,
        yellow,
        corner,
        teamScoreOT,
        penalty,
    ] = array

    result.teamId = teamId
    result.teamRankInLeague = teamRankInLeague
    result.teamScore = teamScore
    result.teamScoreHalf = teamScoreHalf
    result.red = red
    result.yellow = yellow
    result.corner = corner
    result.teamScoreOT = teamScoreOT
    result.penalty = penalty

    return result
}

export const GameDataArrayToObject = (array) => {


    let result = {}
    const [
        matchId,
        eventId,
        status,
        schedule,
        startAt,
        homeTeam,
        awayTeam,
        gameInfo,
        seasonInfo,
        stageInfo,
        gameIndex,
    ] = array

    result.matchId = matchId
    result.eventId = eventId
    result.status = status
    result.schedule = schedule
    result.startAt = startAt
    result.homeTeam = teamDataArrayToObject(homeTeam)
    result.awayTeam = teamDataArrayToObject(awayTeam)
    result.gameInfo = gameInfo
    result.seasonInfo = seasonInfo
    result.stageInfo = stageInfo
    result.gameIndex = gameIndex

    return result
}

export const GameDataObjectFinalized = (game, teams, events, stages = []) => {
    const result = {...game}
    const {
        homeTeam,
        awayTeam,
        eventId,
        stageInfo,
    } = game

    const homeTeamId = homeTeam.teamId
    const awayTeamId = awayTeam.teamId
    const stageId = stageInfo[0]

    const homeTeamDetail = teams[homeTeamId]
    const awayTeamDetail = teams[awayTeamId]
    const event = events[eventId]

    if (homeTeamDetail === undefined || awayTeamDetail === undefined) {
        return {}
    }
    result.homeTeam.detail = homeTeamDetail ? homeTeamDetail : {}
    result.awayTeam.detail = awayTeamDetail ? awayTeamDetail: {}
    result.event = event
    if (stages !== []) {
        result.stage = stages[stageId]
    }
    return result
}
